﻿using NetFramework;
using System;
/*
* 作 者: 槐尧
* 公司： 你懂的
*/
using System.Collections;
using System.Collections.Generic;
using System.IO;


public class ServerDll
{
    public static Dictionary<string, ClientInfo> m_clients = new Dictionary<string, ClientInfo>();
    public static Dictionary<string, Action<string, Dictionary<string, object>>> actionDeal = new Dictionary<string, Action<string, Dictionary<string, object>>>();
    private static List<string> m_ipConfig ;
    private static bool m_beIgnoreIp = false;



    public static void AddRouteHandel(string route, Action<string, Dictionary<string, object>> action)
    {
        actionDeal[route] = action;
    }

    public static void DealMessage(string connectedId,string message)
    {
        try
        {
            Dictionary<string, object> messageJson = Json.Deserialize(message) as Dictionary<string, object>;
            if (messageJson != null)
            {
                string route = DictionaryUnity.GetSafeStringValue(messageJson, "route");
                Action<string, Dictionary<string, object>> action = null;
                if (actionDeal.TryGetValue(route, out action))
                {
                    action(connectedId, messageJson);
                }
                else
                {
                    Console.WriteLine("can not find route " + route);
                }
                
            }
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(message);
        }
    }

    /// <summary>
    /// 网络连接
    /// </summary>
    /// <param name="user"></param>
    public static void ConnectClient(AsyncUserToken user)
    {
        string connectId = user.ConnectionId;
        ClientInfo client = null;
        if (!m_clients.TryGetValue(connectId, out client))
        {
            client = new ClientInfo();
            client.connectedId = connectId;
            client.ipAddress = user.EndPoint.Address.ToString();
            m_clients.Add(connectId, client);
        }
    }

    public static ClientInfo GetClientById(string connectId)
    {
        ClientInfo client = null;
        m_clients.TryGetValue(connectId, out client);
        return client;
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    /// <param name="user"></param>
    public static void DisconnectClient(AsyncUserToken user)
    {
        string connectId = user.ConnectionId;
        ClientInfo client = null;
        if (m_clients.TryGetValue(connectId, out client))
        {
            m_clients.Remove(connectId);
        }
    }

    /// <summary>
    /// 获取IP配置
    /// </summary>
    /// <returns></returns>
    public static List<string> GetIpCpnfig()
    {
        m_ipConfig = new List<string>();
        string filePath = System.Environment.CurrentDirectory + "/ipconfig";
        if (!File.Exists(filePath))
        {
            Dictionary<string, object> ipConfig = new Dictionary<string, object>();
            ipConfig["ignoreIp"] = 0;
            ipConfig["ips"] = new List<object>();
            FileManager.WriteBytes(filePath, Json.Serialize(ipConfig));
            return m_ipConfig;
        }
        else
        {
            string content = FileManager.ReadFile(filePath);
            Dictionary<string, object> ipConfig = Json.Deserialize(content) as Dictionary<string, object>;
            if (ipConfig == null)
            {
                m_beIgnoreIp = false;
                return m_ipConfig;
            }
            else
            {
                m_beIgnoreIp = DictionaryUnity.GetSafeIntValue(ipConfig, "ignoreIp") == 1;
                List<object> lst = ipConfig["ips"] as List<object>;
                if (lst == null)
                {
                    FileManager.WriteBytes(filePath, "[]");
                    return m_ipConfig;
                }

                foreach (object o in lst)
                {
                    m_ipConfig.Add(o.ToString());
                }
            }
            

            return m_ipConfig;
        }
    }

    private static void SaveIpconfig()
    {
        Dictionary<string, object> ipConfig = new Dictionary<string, object>();
        ipConfig["ignoreIp"] = m_beIgnoreIp ? 1 : 0;
        

        List<object> obj = new List<object>();
        foreach (string ip in m_ipConfig)
        {
            obj.Add(ip);
        }
        ipConfig["ips"] = obj;

        string filePath = System.Environment.CurrentDirectory + "/ipconfig";
        string content = Json.Serialize(ipConfig);
        FileManager.WriteBytes(filePath, content);
    }

    /// <summary>
    /// 是否在ip范围内
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public static bool BeInLst(string ip)
    {
        return (m_ipConfig.IndexOf(ip) != -1);
    }

    /// <summary>
    /// 增加到配置文件
    /// </summary>
    /// <param name="ip"></param>
    public static bool AddIpConfig(string ip)
    {
        if (!BeInLst(ip))
        {
            m_ipConfig.Add(ip);
            SaveIpconfig();
            return true;
        }
        return false;
    }

    public static void DeleteIpConfig(string ip)
    {
        if (BeInLst(ip))
        {
            m_ipConfig.Remove(ip);
            SaveIpconfig();
        }
    }


    public static bool BeIgnoreIp
    {
        get 
        {
            if (m_ipConfig == null)
            {
                GetIpCpnfig();
            }
            return ServerDll.m_beIgnoreIp;
        }
        set 
        { 
            ServerDll.m_beIgnoreIp = value;
            SaveIpconfig();
        }
    }

    public static int GetInt(string txt)
    {
        txt = txt.Trim();
        int ret = -1;
        try
        {
            ret = int.Parse(txt);
        }
        catch (System.Exception ex)
        {

        }

        return ret;
    }
}